<?php

namespace app\admin\controller\store;

use app\admin\model\Admin;
use app\admin\model\halt\Cate;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 半成品管理
 *
 * @icon fa fa-circle-o
 */
class Preproduct extends Backend
{
    protected $modelValidate = true;

    /**
     * Preproduct模型对象
     * @var \app\admin\model\Preproduct
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Preproduct;
        $this->view->assign("classifList", $this->model->getClassifList());
    }

    public function import(){
        $file = $this->request->request('file');

        exit;
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $str='';
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();


                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;

                }
            }
            $row['ctime']=time();
            $row['b_n']=uniqid();
            $str=implode(',',array_reverse($this->getPar($row['classif'],true)));
            $strPid=null;
            $row['class_text']= $str;
            if ($row) {

                $insert[] = $row;
            }

        }

        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }
    public function index()
    {
        //设置过滤方法
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where['type']=1;

            $filter=json_decode($this->request->get("filter"),1);
            list($wher, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($filter){
                if (isset($filter['cname']) && $filter['cname']!=''){
                    $cname=$filter['cname'];
                    $where['cname|cnames']=array('like',"{$cname}%");
                }
                if (isset($filter['first'])){
                    //查询弟3级当前分类
                    if (isset($filter['three'])){
                        $where['classif']=array('eq',$filter['three']);

                        //第二级，应该第二下面第三所有
                    }elseif (isset($filter['second'])){
                        $cate = new Cate();
                        $info = collection($cate->where(array('pid'=>$filter['second']))->select())->toArray();
                        if($info){
                            $data = array_column($info,'id');
                            $str = implode(',',$data);
                            $str.=",".$filter['second'];
                        }else{
                            $str=$filter['second'];
                        }
                        $where['classif']=array('in',$str);

                    }else{
                        $data = $this->getChild($filter['first']);
                        if ($data){
                            $str = implode(',',$data);
                            $str.=",".$filter['first'];

                        }else{
                            $str=$filter['first'];

                        }
                        $where['classif']=array('in',$str);


                    }


                }
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $stDb = new \app\admin\model\Stock();

            foreach ($list as $k=>$v){
               // $list[$k]['cname'] = $v['cname'];
                $list[$k]['className']=$this->getName($v['class_text']);
                $list[$k]['ctime']=date("Y-m-d",$v['ctime']);
               $sql="select sum(num) as num from hdyj_stock where shopid={$v['id']} group by shopid";
                $info=$stDb->query($sql);
                if (isset($info[0])) {
                    $list[$k]['storenum'] = $info[0]['num'];
                }else{
                    $list[$k]['storenum'] = 0;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function view($ids){
        $type = isset($_GET['type']) ? intval($_GET['type']) : 1;
        if ($type==1){
            $list = Db::name('houseout')->where(array("shopid"=>$ids))->paginate(10, false, ['query' => request()->param()]);

        }else{
            $list = Db::name('house_in')->where(array("shopid"=>$ids))->paginate(10, false, ['query' => request()->param()]);

        }
        $this->assign('list', $list);
        $this->assign('type', $type);

        return $this->view->fetch();
    }
   public function test(){
        $a = $this->getPar(17);
         $a= array_reverse($a);
        var_dump($a);
    }
    protected function getPar($pid,$clear=false)
    {

        static $strPid = array();
        if ($clear) {

             $strPid = array();
         }
        if ($pid != 0){
            $strPid []= $pid;

        }
        $model = new Cate();
        $data = $model->field('pid')->where(array('id'=>$pid))->find();
        if ($data){
            $this->getPar($data['pid']);
        }

        return $strPid;

    }
    //获取当前子分类
    protected function getChild($pid){
        $arr = array();

        $model = new Cate();
        $data = $model->where(array('pid'=>$pid))->select();
        if ($data){
            foreach ($data as $v){
                $arr[]=$v['id'];
                $arr = array_merge($arr,$this->getChild($v['id']));

            }
        }
        return $arr;
    }
    protected function getName($name){
        if (empty($name))return;
        $arr = explode(",",$name);
        $model = new Cate();
        $str=array();
        foreach ($arr as $v){
            $info = $model->field('name')->find($v);
            if ($info){
                $str[]=$info['name'];
            }
        }
        return implode(',',$str);
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $post = $this->request->post("area/a");
                    $absult=array();
                    $class=0;
                    foreach ($post as $k=>$v){
                        if ($v!=''){
                            $absult[]=$v;
                            $class=$v;
                        }
                    }

                    $abstr = implode(',',$absult);

                    $params['classif']=$class;
                    $params['class_text']=$abstr;
                    $params['type']=1;

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("bh",uniqid());
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $post = $this->request->post("area/a");
                    $absult=array();
                    $class=0;
                    foreach ($post as $k=>$v){
                        if ($v!=''){
                            $absult[]=$v;
                            $class=$v;
                        }
                    }

                    $abstr = implode(',',$absult);

                    $params['classif']=$class;
                    $params['class_text']=$abstr;

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 选择商品
     */
    public function select()
    {
        if ($this->request->isAjax())
        {
            return $this->index();
        }
        return $this->view->fetch();
    }

}
